const express = require('express')
const service = require('./access_token.service')
const knexClient = require('../../../helper/knexClient')
const validateRequest = require('../../../middleware/validateRequest')
const requireRequestContextRole = require('../../../middleware/requireRequestContextRole')
const validations = require('./access_token.validation')
const StatusCode = require('../../../constant/StatusCode')
const Role = require('../../../constant/Role')

const router = express.Router()
const routerPath = '/access_token'

router.get(
  routerPath,
  requireRequestContextRole(Role.ADMINISTRATOR),
  validateRequest(validations.find),
  async (req, res, next) => {
    try {
      const params = req.query
      const result = await service.find(knexClient, params, req.context.accountId)
      return res.json(result)
    } catch (error) {
      return next(error)
    }
  },
)

router.get(
  `${routerPath}/:id`,
  requireRequestContextRole(Role.ADMINISTRATOR),
  validateRequest(validations.get),
  async (req, res, next) => {
    try {
      const { id } = req.params
      const params = req.query
      const record = await service.get(knexClient, id, params, req.context.accountId)
      return res.json(record)
    } catch (error) {
      return next(error)
    }
  },
)

router.delete(
  `${routerPath}/:id`,
  requireRequestContextRole(Role.ADMINISTRATOR),
  validateRequest(validations.delete),
  async (req, res, next) => {
    try {
      const { id } = req.params
      const success = await service.remove(knexClient, id, req.context.accountId)
      return res.json({ success })
    } catch (error) {
      return next(error)
    }
  },
)

module.exports = router
